package org.cainiao.portal.service.impl;

import lombok.RequiredArgsConstructor;
import org.cainiao.portal.dao.service.KnowledgeAreaPointMapperService;
import org.cainiao.portal.dao.service.KnowledgePointDependencyMapperService;
import org.cainiao.portal.dto.response.knowledge.ChartEdge;
import org.cainiao.portal.dto.response.knowledge.ChartGraph;
import org.cainiao.portal.dto.response.knowledge.ChartNode;
import org.cainiao.portal.entity.knowledge.KnowledgePoint;
import org.cainiao.portal.service.KnowledgePointService;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <br />
 * <p>
 * Author: Cai Niao(wdhlzd@163.com)<br />
 */
@Service
@RequiredArgsConstructor
public class KnowledgePointServiceImpl implements KnowledgePointService {

    private final KnowledgeAreaPointMapperService knowledgeAreaPointMapperService;
    private final KnowledgePointDependencyMapperService knowledgePointDependencyMapperService;

    @Override
    public ChartGraph publishedKnowledgePointChart(Long knowledgeAreaId) {
        List<KnowledgePoint> knowledgePoints = knowledgeAreaPointMapperService
            .findKnowledgePointByAreaIdAndPublished(knowledgeAreaId, true);
        if (knowledgePoints.isEmpty()) {
            return ChartGraph.builder().nodes(Collections.emptyList()).edges(Collections.emptyList()).build();
        }

        List<ChartNode> nodes = new ArrayList<>();
        Set<Long> knowledgePointIdSet = new HashSet<>();
        knowledgePoints.forEach(knowledgePoint -> {
            nodes.add(ChartNode.builder().id(knowledgePoint.getId()).name(knowledgePoint.getName()).build());
            knowledgePointIdSet.add(knowledgePoint.getId());
        });
        return ChartGraph.builder().nodes(nodes)
            .edges(knowledgePointDependencyMapperService.findKnowledgePointDependencies(knowledgePointIdSet).stream()
                .map(knowledgePointDependency -> ChartEdge.builder()
                    .from(knowledgePointDependency.getDependencyKnowledgePointId())
                    .to(knowledgePointDependency.getKnowledgePointId()).build()).collect(Collectors.toList())).build();
    }
}
